<template>
  <el-card class="my-product-container">
    <template #header>
      <div class="flex items-center justify-between">
        <h2 class="text-2xl font-semibold text-gray-800">我发布的旧物</h2>
        <el-button type="primary" @click="handlePublish">
          <el-icon>
            <Plus/>
          </el-icon>
          发布商品
        </el-button>
      </div>
    </template>

    <!-- 商品列表 -->
    <div v-loading="loading">
      <el-row v-if="productList.length > 0" :gutter="20">
        <el-col v-for="product in productList" :key="product.id" :span="8" class="mb-5">
          <el-card class="product-item" shadow="hover">
            <div class="product-image-container">
              <el-image
                  :src="product.image?.url"
                  class="product-image"
                  fit="cover"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon>
                      <Picture/>
                    </el-icon>
                  </div>
                </template>
              </el-image>

              <!-- 状态标签 -->
              <div class="product-tags">
                <el-tag v-if="product.status === 1" size="small" type="success">在售</el-tag>
                <el-tag v-else size="small" type="info">已售</el-tag>
              </div>
            </div>

            <div class="product-content">
              <h3 class="product-name">{{ product.name }}</h3>

              <div class="product-info">
                <div class="category-info">
                  <el-tag size="small" type="info">{{ product.categoryName }}</el-tag>
                </div>
                <div class="price-info">
                  <span class="current-price">¥{{ product.price.toFixed(2) }}</span>
                </div>
              </div>

              <div class="product-footer">
                <div class="time-info">
                  <el-icon>
                    <Clock/>
                  </el-icon>
                  <span>{{ product.createTime }}</span>
                </div>

                <div class="action-buttons">
                  <el-button
                      size="small"
                      type="primary"
                      @click="handleEdit(product)"
                  >
                    编辑
                  </el-button>
                  <el-button
                      size="small"
                      type="danger"
                      @click="handleDelete(product)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-empty v-else description="暂无发布的商品"></el-empty>
    </div>

    <!-- 分页组件 -->
    <el-pagination
        v-if="total > 0"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[9, 18, 27]"
        :total="total"
        background
        class="mt-6 flex justify-center"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </el-card>

  <!-- 表单对话框 -->
  <base-dialog
      ref="dialogRef"
      :fields="formFields"
      :title="dialogTitle"
      @submit="handleSubmit"
  />
</template>

<script setup>
import {computed, onMounted, reactive, ref} from 'vue';
import {Clock, Picture, Plus} from '@element-plus/icons-vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import request from '@/utils/request';
import BaseDialog from "@/components/common/BaseDialog.vue";
import {fields} from "@/model/SecondhandGoods.js";

const dialogRef = ref(null)
const dialogTitle = ref(null)
let formFields = computed(() => {
  return fields
})

const handleSubmit = async (formData) => {
  if (formData?.id) {
    await request.put('/secondhandGoods', formData)
    ElMessage.success('更新成功')
  } else {
    await request.post('/secondhandGoods', formData)
    ElMessage.success('添加成功')
  }
  dialogRef.value.close()
  await handleGetMyProducts()
}


// 响应式数据
const loading = ref(false);
const productList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(9);

// 搜索表单数据
const searchForm = reactive({
  page: currentPage.value,
  size: pageSize.value,
  param: {
    publishedByMe: true
  },
  orders: [{
    column: 'createTime',
    asc: false
  }]
});

/**
 * 获取我的商品列表
 */
const handleGetMyProducts = async () => {
  loading.value = true;
  searchForm.page = currentPage.value;
  searchForm.size = pageSize.value;

  const res = await request.post('/secondhandGoods/page', searchForm);
  productList.value = res.records || [];
  total.value = res.total;
  loading.value = false;
};

/**
 * 发布商品
 */
const handlePublish = () => {
  dialogTitle.value = '发布商品'
  dialogRef.value.open({})
};

/**
 * 编辑商品
 */
const handleEdit = (product) => {
  dialogTitle.value = '编辑商品'
  dialogRef.value.open(product)
};

/**
 * 删除商品
 */
const handleDelete = async (product) => {
  try {
    await ElMessageBox.confirm('确认删除该商品？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await request.delete(`/secondhandGoods/${product.id}`);
    ElMessage.success('删除成功');
    await handleGetMyProducts();
  } catch {
    // 用户取消
  }
};

/**
 * 处理每页大小改变
 */
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  handleGetMyProducts();
};

/**
 * 处理当前页码改变
 */
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  handleGetMyProducts();
};

// 组件挂载时获取数据
onMounted(() => {
  handleGetMyProducts();
});
</script>

<style scoped>
.my-product-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.product-item {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.product-item:hover {
  transform: translateY(-2px);
}

.product-image-container {
  position: relative;
  height: 180px;
  overflow: hidden;
}

.product-image {
  border-radius: 10px;
  width: 100%;
  height: 100%;
}

.image-error {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.product-tags {
  position: absolute;
  top: 8px;
  left: 8px;
}

.product-content {
  padding: 15px;
}

.product-name {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 10px 0;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.current-price {
  font-size: 18px;
  font-weight: 600;
  color: #ff4757;
}

.product-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.time-info {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #909399;
}

.action-buttons {
  display: flex;
}

/* 确保分页组件的flex布局能正确居中 */
.el-pagination.is-background .btn-next,
.el-pagination.is-background .btn-prev,
.el-pagination.is-background .el-pager li {
  border-radius: 6px;
}
</style> 